package middleware

import (
	"gitee.com/g_boot/webkit/pathmatch"
	"github.com/gogf/gf/v2/net/ghttp"
	"golang.org/x/exp/slog"
	"net/http"
	"strings"
)

type (
	domainMiddleware struct {
		BaseMiddleware
		// 日志类
		logger slog.Logger
		// 名称
		Name string
		// 是否可用
		Enable bool
		// 检查的域名
		Host string
	}

	DomainOption func(dm *domainMiddleware)
)

func NewDomainMiddleware(name string, options ...DomainOption) *domainMiddleware {
	result := &domainMiddleware{
		Name:   name,
		Enable: true,
	}

	result.logger = *slog.Default()

	for _, option := range options {
		option(result)
	}

	return result
}

func WithDomainEnanle(enable bool) DomainOption {
	return func(mm *domainMiddleware) {
		mm.Enable = enable
	}
}

func WithDomainHost(host string) DomainOption {
	return func(mm *domainMiddleware) {
		mm.Host = host
	}
}

func (s *domainMiddleware) domainMiddlewareEnable() (result bool) {
	result = false
	if !s.Enable {
		s.logger.Debug(s.Name + "禁用中间件")
		return
	}
	result = true

	return
}

func (s *domainMiddleware) Handle(r *ghttp.Request) {
	if s.domainMiddlewareEnable() {

		match := false
		host := strings.Split(r.Host, ":")[0]
		match, err := pathmatch.Match(s.Host, host)
		if !match || err != nil {
			s.logger.Error(host + "域名不匹配")
			r.Response.WriteStatusExit(http.StatusForbidden, "未授权的访问域名！")
		}
		r.Middleware.Next()
	} else {
		r.Middleware.Next()
	}

}
